<template>
  <div class="capital">
    <h2 class="f-cb">
      {{ $t("account.capital.56hq6ym33v00")
      }}<span class="AccountTips" @click="DescriptionOpenShow = true"></span>
      <span class="fr"
        >{{ $t("account.capital.56hqc5m360s0") }}：{{ updateTime | time }}</span
      >
    </h2>
    <!--  成交分布-->
    <div id="deal" ref="deal"></div>
    <h2 style="text-align: right">
      <span>{{ $t("account.capital.56hq6ym35280") }}</span>
    </h2>
    <div class="flowTo f-cb">
      <div id="inflow" class="fl box" ref="bar">
        <!-- 流入 -->
      </div>
      <div id="outflow" class="fr box" ref="bars">
        <!-- 流出 -->
      </div>
    </div>
    <div class="flowTo on f-cb">
      <div class="fl box">
        {{ $t("account.capital.56hq6ym35f00") }}
        <span class="red">{{ barInSum.toFixed(2) }}</span>
      </div>
      <div class="fr box">
        {{ $t("account.capital.56hq6ym35o00") }}
        <span class="green">{{ barOutSum.toFixed(2) }}</span>
      </div>
    </div>
    <h2 class="f-cb on">
      {{ $t("account.capital.56hq6ym360s0") }}
      <span class="fr"
        >{{ $t("account.capital.56hqc5m360s0") }}：{{ updateTime | time }}</span
      >
    </h2>
    <div id="CashTrend" ref="line"></div>
    <el-dialog
      width="700px"
      :visible="DescriptionOpenShow"
      :append-to-body="true"
      :show-close="false"
      :destroy-on-close="true"
      top="14%"
      class="tip_dialog"
    >
      <CapitalExplain @hidePan="hidePan" :type="1"></CapitalExplain>
    </el-dialog>
  </div>
</template>
<script>
import {get_capital} from '@/assets/js/API/info.js';
import CapitalExplain from "@/components/tip/explain";
export default {
  components: {
    CapitalExplain,
  },
  data() {
    return {
      yellow: ["#DE403F"], //第一个为背景色 第二个为边框和文字色
      green: ["#2EB85E"],
      pie: [],
      pieOption: null,
      pieMychar: null,
      nameTitle: "",
      lang: "zh-CN",
      langList: {},
      piesData: [],
      upColor: "#F9293E",
      downColor: "#00aa3b",
      pieRedcolor: [
        "#3ecc70",
        "#2eb85e",
        "#1e9f4b",
        "#ff4a49",
        "#de403f",
        "#c33837",
      ],
      pieGreencolor: [
        "#ff4a49",
        "#de403f",
        "#c33837",
        "#3ecc70",
        "#2eb85e",
        "#1e9f4b",
      ],
      redcolor: ["#ff4a49", "#de403f", "#c33837"],
      greencolor: ["#3ecc70", "#2eb85e", "#1e9f4b"],
      barInSum: 0,
      barOutSum: 0,
      updateTime: "",
      timeArr: [],
      dataLine: [],
      screenWidth: document.body.clientWidth, // 屏幕宽度
      leftBar: [],
      rightBar: [],
      formObj: this.$store.state.index.StockData,
      times: null,
      Xdata: [
        this.$i18n.t("m.caName1"),
        this.$i18n.t("m.caName2"),
        this.$i18n.t("m.caName3"),
      ],
      DescriptionOpenShow: false,
    };
  },
  mounted() {
    var _this = this;
    this.$nextTick(function () {
      _this.postClick();
    });
  },
  computed: {
    Moneylist() {
      return [
        { value: "SSE", label: this.$i18n.t("m.cnMoney") },
        { value: "SZSE", label: this.$i18n.t("m.cnMoney") },
        { value: "HKEX", label: this.$i18n.t("m.hkMoney") },
        { value: "US", label: this.$i18n.t("m.usMoney") },
      ];
    },
  },
  filters: {
    time(value) {
      if (!value) {
        return "--";
      }
      value = value.toString();
      var year = value.substr(0, 4);
      var month = value.substr(4, 2);
      var day = value.substr(6, 2);
      var hour = value.substr(8, 2);
      var Minutes = value.substr(10, 2);
      return year + "-" + month + "-" + day + " " + hour + ":" + Minutes;
    },
  },
  beforeDestroy() {
    clearInterval(this.times); //关闭
    this.times = null;
  },
  created() {
    this.timeDateList();
  },
  methods: {
    postClick() {
      var _this = this;
      if (sessionStorage.getItem("color") == "RedRose") {
        _this.pies(_this.piesData, _this.pieRedcolor);
      } else {
        _this.pies(_this.piesData, _this.pieGreencolor);
      }
      this.bar(this.Xdata, this.leftBar, this.redcolor, "bar");
      this.bar(this.Xdata, this.rightBar, this.greencolor, "bars");
      this.line("line", this.dataLine);
      this.getCapitals(this.$store.state.index.StockData);
    },
    hidePan() {
      this.DescriptionOpenShow = false;
    },
    //关闭弹框
    ClosePopup(msg) {
      this[msg] = false;
    },
    setInt(obj) {
      var _this = this;
      clearInterval(this.times); // 关键
      _this.times = null;
      _this.times = setInterval(() => {
        _this.getCapitals(obj);
      }, 5000);
    },
    //获取数据
    getCapitals(obj) {
      var _this = this;
        get_capital(obj).then(function (res) {
          if (res.code == 1) {
            _this.updateTime = res.data.updateTime;
            var barIn = res.data.dist.in;
            var barOut = res.data.dist.out;
            _this.piesData = [
              {
                //顺时针 绿色开始
                value: barOut.maxAmount,
              },
              {
                value: barOut.midAmount,
              },
              {
                value: barOut.minAmount,
              },
              {
                value: barIn.maxAmount,
              },
              {
                value: barIn.midAmount,
              },
              {
                value: barIn.minAmount,
              },
            ];

            if (sessionStorage.getItem("color") == "RedRose") {
              _this.pies(_this.piesData, _this.pieRedcolor);
            } else {
              _this.pies(_this.piesData, _this.pieGreencolor);
            }

            //求和
            _this.leftBar = [
              _this.forBar(barIn.maxAmount),
              _this.forBar(barIn.midAmount),
              _this.forBar(barIn.minAmount),
            ];
            _this.rightBar = [
              _this.forBar(barOut.maxAmount),
              _this.forBar(barOut.midAmount),
              _this.forBar(barOut.minAmount),
            ];

            _this.barInSum = _this.leftBar.reduce(
              (prev, next, index, array) => Number(prev) + Number(next)
            );
            _this.barOutSum = _this.rightBar.reduce(
              (prev, next, index, array) => Number(prev) + Number(next)
            );
            if (sessionStorage.getItem("color") == "RedRose") {
              _this.bar(_this.Xdata, _this.leftBar, _this.redcolor, "bar");
              _this.bar(_this.Xdata, _this.rightBar, _this.greencolor, "bars");
            } else {
              _this.bar(_this.Xdata, _this.leftBar, _this.greencolor, "bar");
              _this.bar(_this.Xdata, _this.rightBar, _this.redcolor, "bars");
            }
            var arr = res.data.flow.map(function (item) {
              if (item.date.toString().length == 10) {
                var DAte = new Date(item.date * 1000);
                var timeIndex =
                  (DAte.getHours() < 10
                    ? "0" + DAte.getHours()
                    : DAte.getHours()) +
                  ":" +
                  (DAte.getMinutes() < 10
                    ? "0" + DAte.getMinutes()
                    : DAte.getMinutes());
                _this.getArrEqual(timeIndex, item.chg);
              }
            });
            _this.line("line", _this.dataLine);
            // setTimeout(function(){
            //     _this.getCapitals();
            // },5000)
          } else {
            _this.$message({
              message: response.data.msg,
              type: "warning",
            });
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    forBar(el, less) {
      el = Number(el);
      if (this.lang == "zh-CN") {
        return (el / 10000).toFixed(2);
      } else {
        return (el / 1000000).toFixed(2);
      }
    },
    //成交分布
    pies(data, colorList) {
      //console.log(data,colorList,'getCapitals')
      var mychar = this.$echarts.init(this.$refs.deal);
      var option = {
        title: {
          subtext: "",
          left: "center",
          top: "43%",
          subtextStyle: {
            color: "#fff",
            fontSize: 14,
          },
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "80%"],
            center: ["50%", "58%"], //设置饼图位置
            silent: true,
            label: {
              formatter: "{d}%  ",
            },
            labelLine: {
              show: true,
              length: 5,
            },
            itemStyle: {
              normal: {
                //这里是重点
                color: function (params) {
                  //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                  if (params.dataIndex)
                    console.log(
                      params.dataIndex,
                      colorList[params.dataIndex],
                      "colorList[params.dataIndex]"
                    );
                  return colorList[params.dataIndex];
                },
              },
            },
            data: data,
          },
        ],
      };
      //console.log(data,colorList,'getCapitals')
      mychar.setOption(option, true);
    },
    bar(Xdata, servData, color, bar) {
      var mychar = this.$echarts.init(this.$refs[bar]);
      var option = {
        color: color,
        tooltip: {
          show: false,
          trigger: "item",
          formatter:
            "{b}: {c}" + this.lang == "zh"
              ? this.$t("account.capital.56hq6ym36ao0")
              : "ten thousand",
          triggerOn: "mousemove|click",
          confine: true,
          backgroundColor: "rgba(50,50,50,0.5)",
          position: function (pos, params, dom, rect, size) {
            // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
            // var obj = {top: 60};
            // obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = pos;
            return [rect.x - 40, rect.y];
          },
        },
        grid: {
          x: "0",
          width: "98%",
          height: "68%",
          bottom: "18%",
        },

        xAxis: [
          {
            type: "category",
            axisLine: {
              lineStyle: {
                color: "#B0B0B2",
                type: "dashed",
              },
            },
            axisTick: {
              show: false,
              interval: 0,
            },
            axisLabel: {
              color: "#999",
              fontSize: 12,
            },
            data: Xdata,
          },
        ],
        yAxis: [
          {
            type: "value",
            show: false,
          },
        ],
        series: [
          {
            type: "bar",
            barWidth: "50%",
            barGap: "15%",
            label: {
              fontSize: 10,
              show: true,
              position: "top",
              color: "#fff",
            },
            data: servData,
            itemStyle: {
              normal: {
                //这里是重点
                color: function (params) {
                  //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                  var colorList = color;
                  return colorList[params.dataIndex];
                },
              },
            },
          },
        ],
      };
      mychar.setOption(option, true);
    },
    getArrEqual(time, lineData) {
      var i1 = this.timeArr.findIndex((value) => value == time);
      this.dataLine[i1] = lineData;
      // return newArr;
    },
    //资金流向趋势
    line(el, data1) {
      var mychar = this.$echarts.init(this.$refs[el]);
      var option = {
        grid: {
          height: "95%",
          width: "90%",
          y: "9",
          x: "15",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          axisLabel: {
            color: "#999",
            align: "center",
            interval: Math.floor(this.timeArr.length / 2),
            showMinLabel: true,
            showMaxLabel: true,
            margin: 15,
          },
          axisTick: {
            show: false,
          },
          boundaryGap: true,
          data: this.timeArr,
        },
        yAxis: {
          type: "value",
          axisLabel: {
            inside: true,
            // color:function(val){
            //   if(sessionStorage.getItem("color")=='RedRose'){
            //     return val < 0 ? 'green' : val==0?'#B0B0B2':'red';
            //   }else {
            //     return val < 0 ? 'red' : val==0?'#B0B0B2':'green';
            //   }
            // },
            color: "#B0B0B2",
            formatter: function (value, idx) {
              if (value == 0) {
                return 0;
              } else {
                return value / 1000000 + "M";
              }
            },
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            //y轴刻度线
            show: false,
          },
          splitNumber: 2,
        },
        series: [
          {
            data: data1,
            type: "line",
            showSymbol: false,
            connectNulls: true,
            lineStyle: {
              color: "#448EF6",
              width: 1,
            },
          },
        ],
      };
      mychar.setOption(option, true);
    },
    timeDateList() {
      var timeArr = new Array();
      if (["SSE", "SZSE"].includes(this.formObj.market)) {
        timeArr.push("09:30");
        timeArr.concat(this.getNextTime("09:30", "11:30", 1, timeArr));
        timeArr.push("13:00");
        timeArr.concat(this.getNextTime("13:00", "16:00", 1, timeArr));
      } else if (["US"].includes(this.formObj.market)) {
        timeArr.push("09:30");
        timeArr.concat(this.getNextTime("09:30", "12:45", 1, timeArr));
        timeArr.push("12:45");
        timeArr.concat(this.getNextTime("12:45", "16:00", 1, timeArr));
      } else if (["HKEX"].includes(this.formObj.market)) {
        timeArr.push("09:30");
        timeArr.concat(this.getNextTime("09:30", "12:00", 1, timeArr));
        timeArr.push("13:00");
        timeArr.concat(this.getNextTime("13:00", "16:00", 1, timeArr));
      }
      this.timeArr = timeArr;
      this.dataLine.length = timeArr.length;
      this.dataLine.fill("-");
    },
    getNextTime(startTime, endTIme, offset, resultArr) {
      var result = this.addTimeStr(startTime, offset);
      resultArr.push(result);
      if (result == endTIme) {
        return resultArr;
      } else {
        return this.getNextTime(result, endTIme, offset, resultArr);
      }
    },
    addTimeStr(time, num) {
      var hour = time.split(":")[0];
      var mins = Number(time.split(":")[1]);
      var mins_un = parseInt((mins + num) / 60);
      var hour_un = parseInt((Number(hour) + mins_un) / 24);

      if (mins_un > 0) {
        if (hour_un > 0) {
          var tmpVal = ((Number(hour) + mins_un) % 24) + "";
          hour = tmpVal.length > 1 ? tmpVal : "0" + tmpVal; //判断是否是一位
        } else {
          var tmpVal = Number(hour) + mins_un + "";
          hour = tmpVal.length > 1 ? tmpVal : "0" + tmpVal;
        }
        var tmpMinsVal = ((mins + num) % 60) + "";
        mins = tmpMinsVal.length > 1 ? tmpMinsVal : 0 + tmpMinsVal; //分钟数为 取余60的数
      } else {
        var tmpMinsVal = mins + num + "";
        mins = tmpMinsVal.length > 1 ? tmpMinsVal : "0" + tmpMinsVal; //不大于整除60
      }
      return hour + ":" + mins;
    },
  },
  watch: {
    "$store.state.index.StockData": {
      handler(val, old) {
        if (val !== "") {
          var _this = this;
          _this.formObj = val;
          _this.$nextTick(function () {
            _this.postClick(val);
          });
        }
      },
      deep: true,
    },
  },
};
</script>
<style lang="less">
@import "~@/assets/less/tip_dialog";
.capital {
  padding: 10px 0 70px;
  width: 100%;
  h2 {
    font-size: 12px;
    color: @fff;
    line-height: 32px;
    padding-bottom: 37px;
    padding: 0 20px;
    span {
      color: @fbSix;
    }
    .AccountTips {
      width: 15px;
      height: 15px;
      display: inline-block;
      margin-left: 3px;
      cursor: pointer;
      background: url(~@/assets/img/icon_bbxxh.png) no-repeat center;
      background-size: 100% auto;
      position: relative;
      top: 3px;
    }
  }
  h2.on {
    border-top: 1px solid @LightBorderLine;
    margin-top: 15px;
    padding: 10px 20px;
  }
  #deal {
    width: 340px;
    height: 200px;
    margin: 0 auto;
    position: relative;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
  .flowTo {
    padding: 0 20px;
    .box {
      width: 165px;
      height: 140px;
    }
  }
  .flowTo.on {
    .box {
      height: auto;
      color: @fff;
      font-size: 12px;
      text-align: center;
      line-height: 32px;
    }
  }
  #CashTrend {
    width: 376px;
    height: 200px;
    position: relative;
    padding: 0 20px;
    box-sizing: border-box;
  }
}
.Description {
  margin: 0 !important;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .el-dialog__body {
    h2 {
      color: @fff;
      font-size: 14px;
      line-height: 24px;
      padding-left: 0;
      padding-bottom: 15px;
    }
    p {
      font-size: 12px;
      color: @fbSix;
      line-height: 20px;
    }
  }
}
</style>